import React from 'react';
import { Image, SafeAreaView, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import { BackImageOn, XMHeader, msg, XMEmpty, Button, Loading } from '@/common';
import { px2dp } from '@/styles';
import { empty05, iconRightGray } from '@/images';

import supply from '@/api/supply';
import { debounce } from '@/common/util';
import SearchInput from '../../components/search-input';
import ModalBox from './components/modal-box';
import SectionListContacts from '../../components/section-list-contacts';

const { Submit } = Button;

export default class MyDrive extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      driverPhone: '',
      modalIsShow: false,
      driverList: [],
      searchText: '',
      search: false,
      isLoading: true
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    this.getCustDriverList('', false);
  }

  // 自定义头部
  renderHeader = () => {
    const { search } = this.state;
    return (
      <XMHeader
        renderLeft={() => {
          return (
            <BackImageOn onClick={() => {
              msg.emit('router: back');
            }}
            />

          );
        }}
        renderTitle={() => {
          return (
            <Text style={{ color: '#333232', fontSize: px2dp(32), fontWeight: 'bold' }}>我的司机</Text>
          );
        }}
        renderRight={() => {
          return (
            <>
              {
                search && (
                  <TouchableOpacity
                    onPress={() => this._changeIsShow(true)}
                  >
                    <Text
                      style={{
                        color: '#BA914A',
                        fontSize: px2dp(32),
                        marginRight: px2dp(16)
                      }}
                    >
                      + 添加司机
                    </Text>
                  </TouchableOpacity>
                )
              }
            </>
          );
        }}
      />
    );
  }

  render() {
    const { driverPhone, modalIsShow, search, isLoading } = this.state;
    return (
      <SafeAreaView style={{ flex: 1 }}>
        {this.renderHeader()}
        <View style={{ paddingHorizontal: px2dp(20), flex: 1 }}>
          {
            search &&
            <SearchInput
              placeholder='搜索姓名、手机号'
              onChangeText={text => {
                this.setState({ searchText: text }, () => {
                  this.getCustDriverList(text, true);
                });
              }}
            />
          }

          { isLoading && <Loading /> }

          { this.rendeRriverList()}

          <ModalBox
            isShow={modalIsShow}
            driverPhone={driverPhone}
            changePhone={phone => this._changePhone(phone)}
            determine={() => this._determine()}
            changeIsShow={show => this._changeIsShow(show)}
          />
        </View>
      </SafeAreaView>
    );
  }

  rendeRriverList = () => {
    const { isLoading, driverList, searchText } = this.state;
    if (!isLoading) {
      if (driverList.length > 0) {
        return (
          <SectionListContacts
            source={driverList}
            firstWord='driverName'
            renderItem={item => this._renderItem(item.item)}
          />
        );
      }
      let text = searchText ? '暂未搜索到相关司机' : '您暂时还没有司机噢~';
      return (
        <XMEmpty
          emptyImg={empty05}
          desc={text}
          boxStyle={{
            marginTop: px2dp(180),
          }}
          renderFooter={() => {
            if (!searchText) {
              return (
                <Submit
                  text='+ 添加司机'
                  boxStyle={{
                    width: px2dp(640),
                    height: px2dp(96),
                    borderRadius: px2dp(12),
                    overflow: 'hidden',
                    marginTop: px2dp(80),
                  }}
                  btnStyle={{}}
                  btnTextStyle={{
                    fontSize: px2dp(36),
                  }}
                  onClick={() => {
                    this._changeIsShow(true);
                  }}
                />
              );
            }
          }}
        />
      );
    }
  }

  _renderItem = (item) => {
    const { driverName, driverMobile, state } = item;
    return (
      <TouchableOpacity
        style={styles.driverItem}
        onPress={() => this.getDriverInfo(item)}
      >
        <View style={styles.driverInfoItem}>
          <Text style={[styles.driverNameInfo, { color: '#343332' }]}>{driverName}</Text>
          <Text style={styles.driverPhoneInfo}>{driverMobile}</Text>
        </View>
        {
          state === 2 && (
            <View
              style={{
                width: px2dp(96),
                height: px2dp(48),
                backgroundColor: '#F5F5F5',
                alignItems: 'center',
                justifyContent: 'center',
                borderRadius: px2dp(12)
              }}
            >
              <Text
                style={{
                  color: '#999896',
                  fontSize: px2dp(24) }}
              >
                请假中
              </Text>
            </View>
          )
        }
        {state === 3 && (
          <View
            style={{
              width: px2dp(96),
              height: px2dp(48),
              backgroundColor: '#F5F5F5',
              alignItems: 'center',
              justifyContent: 'center',
              borderRadius: px2dp(12)
            }}
          >
            <Text
              style={{
                color: '#999896',
                fontSize: px2dp(24) }}
            >
              封禁中
            </Text>
          </View>
        )}
        { state === 1 &&
          (<Image
            style={{
              width: px2dp(24),
              height: px2dp(24)
            }}
            source={iconRightGray}
          />)}
      </TouchableOpacity>
    );
  }

  // 改变手机号码触发
  _changePhone = (phone) => {
    this.setState({ driverPhone: phone });
  }

  // 确定
  _determine = () => {
    this.addCustDriver();
  }

  _changeIsShow = (show) => {
    if (!show) {
      this.setState({ driverPhone: '' });
    }
    this.setState({ modalIsShow: show });
  }

  /**
   * 接口调用
   */
  // 获取司机列表
  getCustDriverList = (driver = '', iSearch) => {
    debounce(() => {
      supply.getCustDriverList({
        parm: driver
      }).then(res => {
        if (res.success) {
          if (iSearch) {
            this.setState({ driverList: res.data, isLoading: false });
          } else {
            this.setState({ driverList: res.data, search: res.data.length > 0, isLoading: false });
          }
        }
      });
    }, 300);
  }

  // 新增我的司机
  addCustDriver = () => {
    const { driverPhone } = this.state;
    supply.addCustDriver({ mobile: driverPhone }).then(res => {
      if (res.success) {
        msg.emit('app:tip', { text: '添加成功' });
        this.getCustDriverList('', false);
        this._changeIsShow(false);
      } else {
        msg.emit('app:tip', { text: res.msg ? res.msg : '添加失败' });
      }
    });
  }

  getDriverInfo = ({ driverId }) => {
    supply.driverInfo({ driverId }).then(res => {
      if (res.success) {
        let data = {
          head: res.data.head ? res.data.head : null,
          name: res.data.name,
          mobile: res.data.mobile,
          joinTime: res.data.joinTime,
          driverAge: res.data.driverAge,
          wayBillCount: res.data.waybillCount,
        };
        msg.emit('router: goToNext', {
          routeName: 'DriverDetail',
          data: res.data,
          isDriver: true
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }
}

const styles = StyleSheet.create({
  headerBackImg: {
    backgroundColor: 'rgba(255,255,255,0.2)',
    paddingLeft: px2dp(16) * 2,
    paddingRight: px2dp(8) * 2,
    paddingTop: px2dp(6) * 2,
    paddingBottom: px2dp(6) * 2,
    borderTopRightRadius: px2dp(50) * 2,
    borderBottomRightRadius: px2dp(50) * 2,
  },
  headerTitle: {
    color: '#333232',
    fontSize: px2dp(36),
    fontWeight: 'bold'
  },
  driverItem: {
    height: px2dp(128),
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: px2dp(1),
    borderBottomColor: '#F0EFEF',
    marginHorizontal: px2dp(20),
  },
  driverInfoItem: {
    flexDirection: 'row',
    flex: 1,
  },
  driverNameInfo: {
    fontSize: px2dp(32),
    marginRight: px2dp(20)
  },
  driverPhoneInfo: {
    color: '#999896',
    fontSize: px2dp(32)
  },
});
